﻿using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Security.Cryptography;
using System.Text;
using System.Web;
using System.Web.Mvc;
using thousandclear.Data;
using thousandClear.Areas.Shop.Models;
using thousandClear.Util.Media;
using thousandClear.Util.Setting;

namespace thousandClear.Areas.Shop.Controllers
{
    public class MessageController : BaseController
    {
        // GET: Shop/Message
        public ActionResult Index(string code, string state, string openid, string logid)
        {
            AppSetting setting = new AppSetting();

            if (string.IsNullOrEmpty(openid))
            {

                openid = GetOpenId(code).openid;

                if (string.IsNullOrEmpty(openid))
                {
                    Response.Redirect(string.Format("https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx719afdb0aa0ebec4&redirect_uri=http%3a%2f%2f{0}%2fshop%2fmain&response_type=code&scope=snsapi_userinfo&state=1#wechat_redirect", setting.AppDomainName.Replace("http://", "")));
                }
            }
            MessageModel model = new MessageModel();
            using (var db = new qianjingEntities())
            {
                var log = db.T_OrderLog.FirstOrDefault(a => a.TOLID.ToString() == logid);
                var order = db.T_Order.FirstOrDefault(a => a.TOID == log.tilTOID);
                var customer = db.O_Customer.FirstOrDefault(a => a.ocOpenid == openid);

                model.ocNicName = customer.ocNicName;
            }
            ViewBag.logid = logid;
            ViewBag.OpenId = openid;
            return View(model);
        }
        public ActionResult Index2(string openid, string code)
        {
            AppSetting setting = new AppSetting();
            if (string.IsNullOrEmpty(openid))
            {
                openid = GetOpenId(code).openid;
                if (string.IsNullOrEmpty(openid))
                {
                    Response.Redirect(string.Format("https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx719afdb0aa0ebec4&redirect_uri=http%3a%2f%2f{0}%2fshop%2fmain&response_type=code&scope=snsapi_userinfo&state=1#wechat_redirect", setting.AppDomainName.Replace("http://", "")));
                }
            }
            MessageModel model = new MessageModel();
            using (var db = new qianjingEntities())
            {
                var customer = db.O_Customer.FirstOrDefault(a => a.ocOpenid == openid);
                if (customer.ocGrades == null)
                {
                    ViewBag.points = 0;
                }
                else
                {
                    ViewBag.points = Convert.ToInt32(customer.ocGrades == null ? 0 : customer.ocGrades);
                }
                model.ocNicName = customer.ocNicName;
            }
            ViewBag.OpenId = openid;
            return View(model);
        }

        public ActionResult Publish(string code, string state, string openid)
        {
            AppSetting setting = new AppSetting();

            if (string.IsNullOrEmpty(openid))
            {

                openid = GetOpenId(code).openid;

                if (string.IsNullOrEmpty(openid))
                {
                    Response.Redirect(string.Format("https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx719afdb0aa0ebec4&redirect_uri=http%3a%2f%2f{0}%2fshop%2fmain&response_type=code&scope=snsapi_userinfo&state=1#wechat_redirect", setting.AppDomainName.Replace("http://", "")));
                }
            }
            ViewBag.OpenId = openid;
            return View();
        }
        // GET: Shop/Wall
        public ActionResult Wall(string code, string state, string openid)
        {

            int page = 1;
            int count = int.MaxValue;
            int currentPage = page;
            int pageCount = count;
            int totalPage = 1;
            int totalCount = 0;
            AppSetting setting = new AppSetting();
            List<MessageModel> list = new List<MessageModel>();

            string access_token = "";
            string UserName = "";
            string headimage = "";

            openid = "ohm5Hv0k-AEWtbSE_Gi1wB65QCcw                                                                        ";

            if (string.IsNullOrEmpty(openid))
            {
                var i = GetOpenId(code);
                openid = i.openid;
                access_token = i.access_token;


                if (string.IsNullOrEmpty(openid))
                {
                    Response.Redirect(string.Format("https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx719afdb0aa0ebec4&redirect_uri=http%3a%2f%2f{0}%2fshop%2fMessage%2fwall&response_type=code&scope=snsapi_userinfo&state=1#wechat_redirect", setting.AppDomainName.Replace("http://", "")));
                }

                var tt = GetUserInfo(openid, access_token);
                headimage = tt.headimgurl;
                UserName = tt.nickname;
            }
            string isCanPublish = "0";
            using (var db = new qianjingEntities())
            {
                isCanPublish = "0";
                var customer = db.O_Customer.FirstOrDefault(a => a.ocOpenid == openid);
                if (customer == null)
                {
                    db.O_Customer.Add(new O_Customer
                    {
                        ocOpenid = openid,
                        ocNicName = UserName,
                        CreatedDate = DateTime.Now,
                        ocHeadImage = headimage,
                        RowStatus = 1,
                        ocGrades = 0,
                    });

                    //找到此用户信息判断是否允许评论,新用户禁止评论
                    isCanPublish = "0";

                    db.SaveChanges();

                }
                else
                {
                    //找到此用户信息判断是否允许评论
                    bool iscan = customer.ocIsCanCommon == null ? false : ((bool)customer.ocIsCanCommon);
                    isCanPublish = iscan ? "1" : "0";

                    bool isflg = false;
                    if (!string.IsNullOrEmpty(headimage))
                    {
                        customer.ocHeadImage = headimage;
                        isflg = true;
                    }

                    if (!string.IsNullOrEmpty(UserName))
                    {
                        customer.ocNicName = UserName;
                        isflg = true;
                    }
                    if (isflg)
                    {
                        db.SaveChanges();
                    }
                    
                }

            }

            //找到此用户信息判断是否允许评论 0 代表不行 1 代表可以
            ViewBag.isCanPublish = isCanPublish;


            using (var db = new qianjingEntities())
            {
                var query = db.T_Message_Board.AsQueryable().Where(a => a.RowStatus != 2);
                totalCount = query.Count();
                var WallMessage = query.OrderByDescending(a => a.CreatedDate).Skip((page - 1) * count).Take(count).ToList();
                foreach (var item in WallMessage)
                {
                    string Gooddesc = "";
                    int time = 0;
                    var customer = db.O_Customer.FirstOrDefault(a => a.OCID == item.tmbOCID);
                    var order = db.v_Order.OrderByDescending(oo => oo.CreatedDate).FirstOrDefault(a => a.toOCID == customer.OCID && (a.RowStatus != 4 && a.RowStatus != 0));

                    if (order != null)
                    {
                        Gooddesc = order.ogsDesc;
                        time = Convert.ToInt16(order.ogsTimeMonth);
                    }
                    else
                    {
                        Gooddesc = "";
                        time = 0;
                    }
                    //if (order != null && order.ogsType != 1 && order.ogsType != 7 && order.ogsType != 5)
                    //{
                   
                    //}

                    list.Add(new MessageModel
                    {
                        tmbImg1 = item.tmbImg1,
                        tmbImg2 = item.tmbImg2,
                        tmbImg3 = item.tmbImg3,
                        tmbImg4 = item.tmbImg4,
                        tmbImg5 = item.tmbImg5,
                        tmbImg6 = item.tmbImg6,
                        tmbImg7 = item.tmbImg7,
                        tmbImg8 = item.tmbImg8,
                        tmbImg9 = item.tmbImg9,
                        CreatedDate = item.CreatedDate,
                        tmbDesc = item.tmbDesc,
                        TMBID = item.TMBID,
                        tmbNoname = Convert.ToInt16(item.tmbNoname),
                        RowStatus = item.RowStatus,
                        tmbBack = item.tmbBack,
                        ocNicName = customer.ocNicName,
                        ocHeadImage = customer.ocHeadImage,
                        ogsTimeMonth = time,
                        ogsDesc = Gooddesc,

                    });

                }

                

            }
            //ViewBag.url = string.Format("{0}/{1}/", setting.AppDomainName, "statics/upload/Message/image");
            ViewBag.url = "../../statics/upload/Message/image/";
            ViewBag.OpenId = openid;
            ViewBag.TotalCount = totalCount;
            totalPage = int.Parse((totalCount / count).ToString()) + (totalCount % count == 0 ? 0 : 1);
            ViewBag.TotalPage = totalPage;
            ViewBag.CurrentPage = currentPage;
            ViewBag.PageCount = pageCount;
            return View(list);
        }

        public int comment(string data)
        {
            int i = 0;
            AppSetting setting = new AppSetting();
            ImageResolver resolver = new ImageResolver();
            using (var db = new qianjingEntities())
            {
                var post = JObject.Parse(data);
                int Grades1 = post["Grades1"].Value<int>();
                int Grades2 = post["Grades2"].Value<int>();
                int Grades3 = post["Grades3"].Value<int>();
                string sameto = post["sameto"].Value<string>();
                int noname = post["noname"].Value<int>();
                string openid = post["OpenId"].Value<string>();
                string PartyMemo = post["PartyMemo"].Value<string>();
                string mediaID = post["mediaID"].Value<string>();
                //从微信服务器下载图片
                UtilNS.Util.WriteLog("imgs to download:" + mediaID);
                string finalImg = "";//本地服务器上的文件名
                string accessToken = UtilNS.Util.GetAccessTokenOpen();
                string[] PicMediaIDs = mediaID.Split(',');
                for (int ii = 0; ii < PicMediaIDs.Length; ii++)
                {
                    if (string.IsNullOrWhiteSpace(PicMediaIDs[ii]))
                        continue;
                    try
                    {
                        string URL = string.Format("http://file.api.weixin.qq.com/cgi-bin/media/get?access_token={0}&media_id={1}", accessToken, PicMediaIDs[ii]);
                        WebClient client = new WebClient();
                        string localName = "comment_" + DateTime.Now.ToString("yyyyMMddHHmmss") + new Random().Next(1000).ToString() + ".jpg";
                        string filePath = setting.AppUploadFolder + "\\Message\\Image\\";
                        client.DownloadFile(URL, filePath + localName);
                        finalImg += localName + ",";
                    }
                    catch (Exception ex)
                    {
                        UtilNS.Util.WriteLog("download img from weixin server Error: " + ex.Message);
                    }

                }



                int logid = 0;
                //
                if (post["logid"].Value<string>() != "")
                {
                    logid = post["logid"].Value<int>();
                }
                var customer = db.O_Customer.Where(a => a.ocOpenid == openid).FirstOrDefault();
                var order = db.T_Order.Where(a => a.RowStatus == 5).FirstOrDefault(a => a.toOCID == customer.OCID);
                string aunts = order.toOATID;

                string imgFileName1 = string.Empty;
                string imgFileName2 = string.Empty;
                string imgFileName3 = string.Empty;
                string imgFileName4 = string.Empty;
                string imgFileName5 = string.Empty;
                string imgFileName6 = string.Empty;
                string imgFileName7 = string.Empty;
                string imgFileName8 = string.Empty;
                string imgFileName9 = string.Empty;
                //string filePath = setting.AppUploadFolder + "\\Message\\Image";                
                string[] LocalImgs = finalImg.Split(',');
                for (int j = 0; j < LocalImgs.Length; j++)
                {
                    if (string.IsNullOrWhiteSpace(LocalImgs[j]))
                        continue;
                    if (j == 0)
                        imgFileName1 = LocalImgs[0];
                    if (j == 1)
                        imgFileName2 = LocalImgs[1];
                    if (j == 2)
                        imgFileName3 = LocalImgs[2];
                    if (j == 3)
                        imgFileName4 = LocalImgs[3];
                    if (j == 4)
                        imgFileName5 = LocalImgs[4];
                    if (j == 5)
                        imgFileName6 = LocalImgs[5];
                    if (j == 6)
                        imgFileName7 = LocalImgs[6];
                    if (j == 7)
                        imgFileName8 = LocalImgs[7];
                    if (j == 8)
                        imgFileName9 = LocalImgs[8];
                }


                db.T_Comment.Add(new T_Comment
                {
                    tcGrades1 = Grades1,
                    tcGrades2 = Grades2,
                    tcGrades3 = Grades3,
                    tcGrades8 = aunts,//管家
                    CreatedBy = openid,//评价人
                    tcRemark = PartyMemo,
                    tcTOLID = logid,
                    CreatedDate = DateTime.Now,
                    RowStatus = 1,

                });
                db.SaveChanges();
                if (sameto == "1")
                {
                    var ocid = db.O_Customer.FirstOrDefault(a => a.ocOpenid == openid).OCID;
                    db.T_Message_Board.Add(new T_Message_Board
                    {
                        tmbDesc = PartyMemo,
                        tmbImg1 = imgFileName1,
                        tmbImg2 = imgFileName2,
                        tmbImg3 = imgFileName3,
                        tmbImg4 = imgFileName4,
                        tmbImg5 = imgFileName5,
                        tmbImg6 = imgFileName6,
                        tmbImg7 = imgFileName7,
                        tmbImg8 = imgFileName8,
                        tmbImg9 = imgFileName9,
                        tmbNoname = noname,
                        CreatedDate = DateTime.Now,
                        tmbOCID = Convert.ToInt16(ocid),
                        RowStatus = 1,
                    });


                    //这里需要做两件事情
                    //更新用户的评论状态为不可评论
                    //赠送用户2金币作为评论的奖励
                    var cust = db.O_Customer.Where(oc => oc.ocOpenid.Trim() == openid.Trim()).ToList();
                    if (cust.Count > 0)
                    {
                        var ttu = cust.First();
                        ttu.ocIsCanCommon = false;
                        ttu.UpdatedBy = "评论更新";
                        ttu.UpdatedDate = DateTime.Now;

                        //获取2个金币作为奖励
                        ttu.ocGrades = (ttu.ocGrades == null ? 0.00m : ttu.ocGrades) + 2;

                        var oa = db.O_Address.Where(opq => opq.oasOCID == ttu.OCID).ToList();
                        if (oa.Count > 0)
                        {
                            var kjh = oa.First();
                            string Phone = kjh.osaPhone;
                            string msg = "您好，感谢您对千净的支持，特赠送您2枚金币，可在“千净家政”公众号“个人-我的积分”中查看。【千净家政祝您生活愉快】";
                            qianjing.APP.SendSms tt = new qianjing.APP.SendSms();
                            tt.SendMsg(Phone, msg);
                        }
                    }

                    db.SaveChanges();

                }

            }
            return i;

        }

        [HttpPost]
        [ValidateInput(false)]
        public int publishMessage(string data)
        {
            AppSetting setting = new AppSetting();
            ImageResolver resolver = new ImageResolver();
            var post = JObject.Parse(data);
            int noname = post["noname"].Value<int>();
            string openid = post["OpenId"].Value<string>();
            string PartyMemo = post["PartyMemo"].Value<string>();
            string mediaID = post["mediaID"].Value<string>();
            UtilNS.Util.WriteLog("imgs to download:" + mediaID);
            string finalImg = "";//本地服务器上的文件名
            string accessToken = UtilNS.Util.GetAccessTokenOpen();
            string[] PicMediaIDs = mediaID.Split(',');
            for (int ii = 0; ii < PicMediaIDs.Length; ii++)
            {
                if (string.IsNullOrWhiteSpace(PicMediaIDs[ii]))
                    continue;
                try
                {
                    string URL = string.Format("http://file.api.weixin.qq.com/cgi-bin/media/get?access_token={0}&media_id={1}", accessToken, PicMediaIDs[ii]);
                    WebClient client = new WebClient();
                    string localName = "comment_" + DateTime.Now.ToString("yyyyMMddHHmmss") + new Random().Next(1000).ToString() + ".jpg";
                    string filePath = setting.AppUploadFolder + "\\Message\\Image\\";
                    client.DownloadFile(URL, filePath + localName);
                    finalImg += localName + ",";
                }
                catch (Exception ex)
                {
                    UtilNS.Util.WriteLog("download img from weixin server Error: " + ex.Message);
                }

            }
            int i = 0;
            //string filePath = setting.AppUploadFolder + "\\Message\\Image";
            string imgFileName1 = string.Empty;
            string imgFileName2 = string.Empty;
            string imgFileName3 = string.Empty;
            string imgFileName4 = string.Empty;
            string imgFileName5 = string.Empty;
            string imgFileName6 = string.Empty;
            string imgFileName7 = string.Empty;
            string imgFileName8 = string.Empty;
            string imgFileName9 = string.Empty;

            string[] LocalImgs = finalImg.Split(',');
            for (int j = 0; j < LocalImgs.Length; j++)
            {
                if (string.IsNullOrWhiteSpace(LocalImgs[j]))
                    continue;
                if (j == 0)
                    imgFileName1 = LocalImgs[0];
                if (j == 1)
                    imgFileName2 = LocalImgs[1];
                if (j == 2)
                    imgFileName3 = LocalImgs[2];
                if (j == 3)
                    imgFileName4 = LocalImgs[3];
                if (j == 4)
                    imgFileName5 = LocalImgs[4];
                if (j == 5)
                    imgFileName6 = LocalImgs[5];
                if (j == 6)
                    imgFileName7 = LocalImgs[6];
                if (j == 7)
                    imgFileName8 = LocalImgs[7];
                if (j == 8)
                    imgFileName9 = LocalImgs[8];
            }


            using (var db = new qianjingEntities())
            {


                var ocid = db.O_Customer.FirstOrDefault(a => a.ocOpenid == openid).OCID;
                db.T_Message_Board.Add(new T_Message_Board
                {
                    tmbDesc = PartyMemo,
                    tmbImg1 = imgFileName1,
                    tmbImg2 = imgFileName2,
                    tmbImg3 = imgFileName3,
                    tmbImg4 = imgFileName4,
                    tmbImg5 = imgFileName5,
                    tmbImg6 = imgFileName6,
                    tmbImg7 = imgFileName7,
                    tmbImg8 = imgFileName8,
                    tmbImg9 = imgFileName9,
                    CreatedDate = DateTime.Now,
                    tmbOCID = Convert.ToInt16(ocid),
                    RowStatus = 1,
                    tmbNoname = noname,
                });

                //这里需要做两件事情
                //更新用户的评论状态为不可评论
                //赠送用户2金币作为评论的奖励
                var cust = db.O_Customer.Where(oc => oc.ocOpenid.Trim() == openid.Trim()).ToList();
                if (cust.Count > 0)
                {
                    var ttu = cust.First();
                    ttu.ocIsCanCommon = false;
                    ttu.UpdatedBy = "评论更新";
                    ttu.UpdatedDate = DateTime.Now;

                    //获取2个金币作为奖励
                    ttu.ocGrades = (ttu.ocGrades == null ? 0.00m : ttu.ocGrades) + 2;

                    var oa = db.O_Address.Where(opq => opq.oasOCID == ttu.OCID).ToList();
                    if (oa.Count > 0)
                    {
                        var kjh = oa.First();
                        string Phone = kjh.osaPhone;
                        string msg = "您好，感谢您对千净的支持，特赠送您2枚金币，可在“千净家政”公众号“个人-我的积分”中查看。【千净家政祝您生活愉快】";
                        qianjing.APP.SendSms tt = new qianjing.APP.SendSms();
                        tt.SendMsg(Phone, msg);
                    }

                  
                }


                db.SaveChanges();



            }
            return i;


        }
        /// <summary>
        /// 获取JS Ticket
        /// </summary>
        /// <param name="sURL">页面地址</param>
        /// <returns></returns>
        [HttpPost]
        public string GetJSTicket(string data)
        {
            JObject jObj = new JObject();
            try
            {
                string sURL = "";
                var form = JObject.Parse(data);
                sURL = form["sURL"].Value<string>();

                string appid = "wx719afdb0aa0ebec4";
                string secret = "5cc6d0b4ee723320bc8c1c967ea9fc36";
                string JSApi = UtilNS.Util.GetJSAPI_Ticket_open(appid, secret);
                string sTimestamp = UtilNS.Util.ConvertDateTimeToInt(DateTime.Now).ToString();
                string sNonce = "asdasd";
                string sSignature = "";

                string sTemp = string.Format("jsapi_ticket={0}&noncestr={1}&timestamp={2}&url={3}", JSApi, sNonce, sTimestamp, sURL);
                SHA1 sha;
                ASCIIEncoding enc;

                sha = new SHA1CryptoServiceProvider();
                enc = new ASCIIEncoding();
                byte[] dataToHash = enc.GetBytes(sTemp);
                byte[] dataHashed = sha.ComputeHash(dataToHash);
                sSignature = BitConverter.ToString(dataHashed).Replace("-", "");
                sSignature = sSignature.ToLower();

                jObj["appId"] = appid;
                jObj["timestamp"] = sTimestamp;
                jObj["nonceStr"] = sNonce;
                jObj["signature"] = sSignature;
            }
            catch (Exception ex)
            {
                UtilNS.Util.WriteLog("MessageController GetJSTicket Exception: " + ex.Message);
            }
            return JsonConvert.SerializeObject(jObj);
        }
    }
}